package com.kedacom.demo.websocket.client;

import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Map;

import javax.websocket.ClientEndpointConfig;
import javax.websocket.ContainerProvider;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 5.5.2. Ping The Ping frame contains an opcode of 0x9. A Ping frame MAY include "Application data". Upon receipt of a
 * Ping frame, an endpoint MUST send a Pong frame in response, unless it already received a Close frame. It SHOULD
 * respond with Pong frame as soon as is practical. Pong frames are discussed in Section 5.5.3. An endpoint MAY send a
 * Ping frame any time after the connection is established and before the connection is closed. NOTE: A Ping frame may
 * serve either as a keepalive or as a means to verify that the remote endpoint is still responsive.
 */

public class HoldTest {

	public static void main(String[] args) throws InterruptedException {
		Runner runner1 = new Runner();
		runner1.run();
		Thread.sleep(60 * 1000 * 60);

	}

	static class Runner implements Runnable {

		private Logger logger = LoggerFactory.getLogger(getClass());

		@Override
		public void run() {
			WebSocketContainer container = ContainerProvider.getWebSocketContainer(); // 获取WebSocket连接器，其中具体实现可以参照websocket-api.jar的源码,Class.forName("org.apache.tomcat.websocket.WsWebSocketContainer");
			String uri = "ws://172.16.81.122:8080/demo-websocket/websocket";
			ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
			clientEndpointConfig.getUserProperties().put("org.apache.tomcat.websocket.IO_TIMEOUT_MS", "3000");

			try {
				Session session1 = container.connectToServer(MyWebSocketClient.class, new URI(uri));
				// session1.setMaxIdleTimeout(2000);
				logger.info("MaxIdleTimeout:", session1.getMaxIdleTimeout());
				Map<String, Object> userP = session1.getUserProperties();
				for (String k : userP.keySet()) {
					logger.info(k);
				}

				while (true) {
					Thread.sleep(3000);
					if (session1.isOpen()) {
						session1.getBasicRemote().sendPing(ByteBuffer.allocate(0));
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
